package cn.edu.buu.hospital.service.impl;

import cn.edu.buu.hospital.entity.Doctor;
import cn.edu.buu.hospital.entity.Hospital;
import cn.edu.buu.hospital.mapper.DoctorMapper;
import cn.edu.buu.hospital.service.DoctorService;
import cn.edu.buu.hospital.service.HospitalService;
import cn.edu.buu.hospital.service.VisitService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
/**
 * 医生Service实现类
 */
@Service
public class DoctorServiceImpl implements DoctorService {
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private VisitService visitService;
    @Override
    @Transactional
    public void add(Doctor doctor) {
        doctorMapper.insert(doctor);
    }
    @Override
    @Transactional
    public void removeById(Long doctorId) {
        // 检查医生是否存在
        Doctor doctor = doctorMapper.selectById(doctorId);
        if (doctor == null) {
            throw new RuntimeException("医生不存在，无法删除");
        }
        
        // 检查是否有关联的排班记录
        // 注意：这里需要根据实际的系统设计来实现
        // 如果Visit表中有医生ID字段，可以这样检查
        try {
            // 假设visitService有根据医生ID查询排班的方法
            // 由于我们没有看到完整的visitService接口，这里使用通用查询方法
            // 实际实现时需要根据系统设计调整
            // 如果没有合适的方法，可以直接删除
            // 这里只是作为一个示例
        } catch (Exception e) {
            System.err.println("检查关联排班失败: " + e.getMessage());
        }
        
        // 删除医生
        doctorMapper.deleteById(doctorId);
    }
    @Override
    @Transactional
    public void modify(Doctor doctor) {
        System.out.println("开始编辑医生信息，医生ID: " + doctor.getDoctorId() + ", 科室ID: " + doctor.getDeptId());
        
        try {
            // 表单验证
            if (doctor == null) {
                throw new RuntimeException("医生信息不能为空");
            }
            if (doctor.getDoctorId() == null || doctor.getDoctorId() <= 0) {
                throw new RuntimeException("医生ID无效");
            }
            System.out.println("医生ID验证通过: " + doctor.getDoctorId() + ", 科室ID: " + doctor.getDeptId());
            
            if (doctor.getDoctorName() == null || doctor.getDoctorName().trim().isEmpty()) {
                throw new RuntimeException("医生姓名不能为空");
            }
            if (doctor.getGender() == null || (!"男".equals(doctor.getGender()) && !"女".equals(doctor.getGender()))) {
                throw new RuntimeException("性别必须为男或女");
            }
            if (doctor.getPhone() == null || doctor.getPhone().trim().isEmpty()) {
                throw new RuntimeException("电话号码不能为空");
            }
            if (doctor.getIdCard() == null || doctor.getIdCard().trim().isEmpty()) {
                throw new RuntimeException("身份证号不能为空");
            }
            if (doctor.getHospitalId() == null || doctor.getHospitalId() <= 0) {
                throw new RuntimeException("请选择所属医院");
            }
            if (doctor.getDeptId() == null || doctor.getDeptId() <= 0) {
                throw new RuntimeException("请选择所属科室");
            }
            
            // 设置空值的默认值
            if (doctor.getEmail() == null) {
                doctor.setEmail("");
            }
            
            System.out.println("表单验证通过，准备检查重复数据");
            
            // 检查是否重复（排除当前编辑的医生）
            System.out.println("查询重复数据，手机号: " + doctor.getPhone() + ", 身份证号: " + doctor.getIdCard());
            Doctor dbDoctor = doctorMapper.findByPhoneOrIdCard(doctor.getPhone(), doctor.getIdCard());
            System.out.println("查询结果: " + (dbDoctor != null ? "找到重复数据" : "未找到重复数据"));
            
            if (dbDoctor != null && !dbDoctor.getDoctorId().equals(doctor.getDoctorId())) {
                if (dbDoctor.getPhone().equals(doctor.getPhone())) {
                    throw new RuntimeException("该电话号码已被其他医生使用");
                }
                if (dbDoctor.getIdCard().equals(doctor.getIdCard())) {
                    throw new RuntimeException("该身份证号已被其他医生使用");
                }
            }
            
            System.out.println("重复数据检查通过，准备更新医生信息");
            
            // 执行更新
            int updateResult = doctorMapper.update(doctor);
            System.out.println("更新结果: 影响行数 " + updateResult);
            
            if (updateResult == 0) {
                throw new RuntimeException("更新失败，未找到该医生信息");
            }
            
            // 验证更新是否成功
            Doctor updatedDoctor = doctorMapper.selectById(doctor.getDoctorId());
            System.out.println("医生信息更新成功，医生ID: " + doctor.getDoctorId() + ", 更新后科室ID: " + updatedDoctor.getDeptId());
        } catch (RuntimeException e) {
            System.err.println("编辑医生信息时发生业务异常: " + e.getMessage());
            e.printStackTrace();
            throw e;
        } catch (Exception e) {
            System.err.println("编辑医生信息时发生系统异常: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("系统错误，请稍后重试");
        }
    }


    @Override
    public Doctor findById(Long doctorId) {
        Doctor doctor = doctorMapper.selectById(doctorId);
        if (doctor != null) {
            // 填充医院名称
            if (doctor.getHospitalId() != null) {
                try {
                    Hospital hospital = hospitalService.findById(doctor.getHospitalId());
                    if (hospital != null) {
                        doctor.setHospitalName(hospital.getHospitalname());
                    }
                } catch (Exception e) {
                    // 处理获取医院信息时的异常，不影响医生数据的返回
                    System.err.println("获取医院信息失败: " + e.getMessage());
                }
            }
            // Doctor类中没有科室名称字段，暂不填充科室名称
        }
        return doctor;
    }
    @Override
    public List<Doctor> findAll() {
        return doctorMapper.selectAll();
    }
    @Override
    public PageInfo<Doctor> find(int pageNum, int pageSize, Doctor condition) {
        PageHelper.startPage(pageNum, pageSize);
        List<Doctor> doctorList = doctorMapper.selectByCondition(condition);
        // 填充每个医生的医院名称
        for (Doctor doctor : doctorList) {
            fillHospitalName(doctor);
        }
        return new PageInfo<>(doctorList);
    }
    @Override
    public List<Doctor> findByDeptId(Long deptId) {
        List<Doctor> doctorList = doctorMapper.selectByDeptId(deptId);
        // 填充每个医生的医院名称
        for (Doctor doctor : doctorList) {
            fillHospitalName(doctor);
        }
        return doctorList;
    }
    
    @Override
    public Doctor doctorLogin(String doctorName, String idCard) {
        // 参数验证
        if (doctorName == null || doctorName.trim().isEmpty() || idCard == null || idCard.trim().isEmpty()) {
            return null;
        }
        
        // 根据医生姓名和身份证号查询医生
        Doctor doctor = doctorMapper.findByNameAndIdCard(doctorName, idCard);
        
        // 如果找到医生，设置默认头像
        if (doctor != null && (doctor.getHeadPic() == null || doctor.getHeadPic().isEmpty())) {
            doctor.setHeadPic("doctor.png");
        }
        
        return doctor;
    }
    
    @Override
    public Doctor findByName(String doctorName) {
        // 参数验证
        if (doctorName == null || doctorName.trim().isEmpty()) {
            return null;
        }
        
        // 创建查询条件
        Doctor condition = new Doctor();
        condition.setDoctorName(doctorName);
        
        // 查询医生列表
        List<Doctor> doctorList = doctorMapper.selectByCondition(condition);
        
        // 如果找到医生，返回第一个并填充医院名称
        if (doctorList != null && !doctorList.isEmpty()) {
            Doctor doctor = doctorList.get(0);
            fillHospitalName(doctor);
            return doctor;
        }
        
        return null;
    }
    
    /**
     * 为医生对象填充医院名称
     */
    private void fillHospitalName(Doctor doctor) {
        if (doctor != null && doctor.getHospitalId() != null) {
            try {
                Hospital hospital = hospitalService.findById(doctor.getHospitalId());
                if (hospital != null) {
                    doctor.setHospitalName(hospital.getHospitalname());
                }
            } catch (Exception e) {
                // 处理获取医院信息时的异常，不影响医生数据的返回
                System.err.println("获取医院信息失败: " + e.getMessage());
            }
        }
    }
}